package com.example.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.example.reggie.common.deploy.BaseContext;
import com.example.reggie.common.table.MsgTable;
import com.example.reggie.common.deploy.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否已经登录
 */
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    public static final AntPathMatcher pathMatcher=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {



        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response =(HttpServletResponse) servletResponse;
        log.info("已拦截请求:{}",request.getRequestURI());


        // 1.获取本次请求的URI
        String reqURI=request.getRequestURI();
        String[] urls=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };
        // 2.检查URI是否需要处理
        boolean res = checkURI(urls, reqURI);
        // 3.如果不需要处理则直接放行
        if(res==true){
            log.info("已放行{}",reqURI);
            filterChain.doFilter(request,response);
            return;
        }
        // 4. 判断登录状态
        if(request.getSession().getAttribute("employee")!=null){
            log.info("已放行{}",reqURI);
            Long id=(Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(id);
            filterChain.doFilter(request,response);
            return;
        }
        if(request.getSession().getAttribute("user")!=null){
            log.info("已放行{}",reqURI);
            Long id=(Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(id);
            filterChain.doFilter(request,response);
            return;
        }
        // 5. 若未登录则返回未登录结果
        response.getWriter().write(JSON.toJSONString(R.error(MsgTable.NOT_LOGIN)));
        return;
    }

    /**
     * 路径匹配方法
     * @param urls
     * @param reqURI
     * @return
     */
    public boolean checkURI(String[] urls,String reqURI){
        for (String url : urls) {
            boolean match = pathMatcher.match(url, reqURI);
            if(match){
                return true;
            }
        }
        return false;
    }
}
